package gk.example.activity;

import gk.example.App;
import gk.example.BaseActivity;
import gk.example.bean.DateInfo;
import gk.example.bean.User;
import gk.example.util.DateTimeUtil;
import gk.example.util.T;
import gk.example.view.ProgressDialog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import com.example.gkdate.R;

/**
 * 
 * Description:发布约会页面
 * 
 * @author Wenk.Chan（最新修改者）
 * @version 1.0（最新版本号）
 */
public class AnnounceActivity extends BaseActivity implements OnClickListener {
	private ImageButton mBtnBack;
	private TextView mTvTitle;
	private Button mBtnAnnounceDetail;
	private Button mBtnAnnounceDate;
	private Button mBtnAnnounceTime;
	private Button mBtnAnnouncePlace;
	private Button mBtnAnnounceContact;
	private Button mBtnAnnouncePeople;
	private DatePickerDialog mDatePickerDialog;
	private TimePickerDialog mTimePickerDialog;
	private Calendar mCalendar;
	private Button mBtnAnnounce;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void initView() {
		setContentView(R.layout.activity_announce);
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);
		mTvTitle = (TextView) findViewById(R.id.tv_top_title);
		mBtnAnnounceDetail = (Button) findViewById(R.id.btn_announce_detail);
		mBtnAnnounceDate = (Button) findViewById(R.id.btn_announce_date);
		mBtnAnnounceTime = (Button) findViewById(R.id.btn_announce_time);
		mBtnAnnouncePlace = (Button) findViewById(R.id.btn_announce_place);
		mBtnAnnounceContact = (Button) findViewById(R.id.btn_announce_contact);
		mBtnAnnouncePeople = (Button) findViewById(R.id.btn_announce_people);
		mBtnAnnounce = (Button) findViewById(R.id.btn_announce);
		mProgressDialog = new ProgressDialog();

	}

	@Override
	protected void initEvent() {
		mBtnAnnounce.setVisibility(View.VISIBLE);
		mTvTitle.setText("发布约会");
		mBtnBack.setOnClickListener(this);
		mBtnAnnounceContact.setText(App.BmobUser.getContact());
		mBtnAnnounceDetail.setOnClickListener(this);
		mBtnAnnounceDate.setOnClickListener(this);
		mBtnAnnounceContact.setOnClickListener(this);
		mBtnAnnouncePlace.setOnClickListener(this);
		mBtnAnnounceTime.setOnClickListener(this);
		mBtnAnnouncePeople.setOnClickListener(this);
		mCalendar = Calendar.getInstance();
		mDatePickerDialog = new DatePickerDialog(this, DateSet,
				mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH),
				mCalendar.get(Calendar.DAY_OF_MONTH));
		mTimePickerDialog = new TimePickerDialog(this, TimeSet,
				mCalendar.get(Calendar.HOUR_OF_DAY),
				mCalendar.get(Calendar.MINUTE), true);
		mBtnAnnounce.setOnClickListener(this);
	}

	/**
	 * 日期时间匿名内部类
	 */
	DatePickerDialog.OnDateSetListener DateSet = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			String[] week = { "", "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
			mCalendar.set(Calendar.YEAR, year);
			mCalendar.set(Calendar.MONTH, monthOfYear);
			mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			String date = null;
			if ((monthOfYear + "").getBytes().length == 1) {
				date = year + "-" + "0" + (monthOfYear + 1) + "-" + dayOfMonth;
			}

			if ((dayOfMonth + "").getBytes().length == 1) {
				date = year + "-" + (monthOfYear + 1) + "-" + "0" + dayOfMonth;
			} else {
				date = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
			}
			if ((monthOfYear + "").getBytes().length == 1
					&& (dayOfMonth + "").getBytes().length == 1) {
				date = year + "-" + "0" + (monthOfYear + 1) + "-" + "0"
						+ dayOfMonth;
			}

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd");
			try {
				Date day = simpleDateFormat.parse(date);
				mCalendar.setTime(day);
				mBtnAnnounceDate.setText(date + " "
						+ week[mCalendar.get(Calendar.DAY_OF_WEEK)]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

		}
	};
	TimePickerDialog.OnTimeSetListener TimeSet = new OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
			mCalendar.set(Calendar.MINUTE, minute);
			String hour = null;
			String min = null;
			if ((hourOfDay + "").getBytes().length == 1) {
				hour = "0" + hourOfDay;
			} else {
				hour = hourOfDay + "";
			}
			if ((minute + "").getBytes().length == 1) {
				min = "0" + minute;
			} else {
				min = minute + "";
			}

			String time = hour + ":" + min;
			mBtnAnnounceTime.setText(time);

		}
	};

	/**
	 * 
	 * 描述： 显示选择地点对话框
	 * 
	 * @return void
	 */
	private void showPlaceDialog() {
		final EditText et = new EditText(this);
		et.setHint("请输入地点");
		AlertDialog.Builder builder = new Builder(this);
		builder.setView(et);
		builder.setTitle("选择地点");
		final String[] places = { "神秘岛", "地下铁", "御鼎记", "珠海渔女" };
		builder.setItems(places,
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						mBtnAnnouncePlace.setText(places[which]);
					}
				});
		builder.setNegativeButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mBtnAnnouncePlace.setText(et.getText().toString());
					}
				});
		builder.setPositiveButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/**
	 * 
	 * 描述： 显示选择约会说明对话框
	 * 
	 * @return void
	 */
	private void showDetailDialog() {
		final EditText et = new EditText(this);
		et.setHint("请输入约会说明");
		AlertDialog.Builder builder = new Builder(this);
		builder.setView(et);
		builder.setTitle("约会说明");
		final String[] details = { "无聊求陪玩", "孤独求陪喝奶茶", "组个队一起的疯吧", "一边玩一边交友吧" };
		builder.setItems(details,
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mBtnAnnounceDetail.setText(details[which]);
						detail = details[which];
					}
				});
		builder.setNegativeButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (et.getText().toString().getBytes().length > 20) {
							String temp = et.getText().toString()
									.substring(0, 10);
							mBtnAnnounceDetail.setText(temp + "...");
						} else {
							mBtnAnnounceDetail.setText(et.getText().toString());
						}
						detail = details[which];
					}
				});
		builder.setPositiveButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/**
	 * 
	 * 描述： 显示选择人数对话框
	 * 
	 * @return void
	 */
	private void showPeopleDialog() {

		final EditText et = new EditText(this);
		et.setHint("请输入人数");
		et.setInputType(InputType.TYPE_CLASS_NUMBER);
		AlertDialog.Builder builder = new Builder(this);
		builder.setView(et);
		builder.setTitle("选择人数");
		final String[] places = { "1位", "2位", "3位", "4位", "5位", "6位", "7位",
				"8位", "9位", "10位" };
		builder.setItems(places,
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						mBtnAnnouncePeople.setText(which + 1 + "");

					}
				});
		builder.setNegativeButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mBtnAnnouncePeople.setText(et.getText());
					}
				});
		builder.setPositiveButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	private static final int DATESTATUS_READY = 2;
	private String detail;

	/**
	 * 
	 * 描述： 发布约会
	 * 
	 * @return void
	 */
	private void announceDate() {
		String[] date = mBtnAnnounceDate.getText().toString().split(" ");
		String time = mBtnAnnounceTime.getText().toString();
		String place = mBtnAnnouncePlace.getText().toString();
		String people = mBtnAnnouncePeople.getText().toString();
		String contact = mBtnAnnounceContact.getText().toString();
		if (!(TextUtils.isEmpty(date[0]) || TextUtils.isEmpty(time))) {
			if (DateTimeUtil.isBefore((date[0] + " " + time))) {

			} else {
				T.show(this, "不能小于当前时间", Toast.LENGTH_SHORT);
				return;
			}
		}
		if (!(TextUtils.isEmpty(date[0]) || TextUtils.isEmpty(time)
				|| TextUtils.isEmpty(place) || TextUtils.isEmpty(people)
				|| TextUtils.isEmpty(contact) || TextUtils.isEmpty(detail))) {
			mProgressDialog.setMsg("发布中");
			mProgressDialog.show(getSupportFragmentManager(), "LOADING_DIALOG");
			BmobRelation attender=new BmobRelation();
			attender.add(App.BmobUser);
			DateInfo dateInfo = new DateInfo();
			dateInfo.setAttender(attender);
			dateInfo.setAnnouncer(App.BmobUser);
			dateInfo.setDateDetail(detail);
			dateInfo.setDateDate(date[0] + " " + date[1]);
			dateInfo.setDateTime(time);
			dateInfo.setDatePeople(people);
			dateInfo.setDatePlace(place);
			dateInfo.setDateStatus(DATESTATUS_READY);
			dateInfo.setDateCurrentPeople(1 + "");
			App.DateInfo = dateInfo;
			dateInfo.save(this, new SaveListener() {
				@Override
				public void onSuccess() {
					addDateToUser();
				}

				@Override
				public void onFailure(int arg0, String arg1) {
					mProgressDialog.dismiss();
					T.show(AnnounceActivity.this, "发布失败" + arg1,
							Toast.LENGTH_SHORT);
				}
			});
		} else {
			T.show(this, "请完整填写信息", Toast.LENGTH_SHORT);
		}
	}

	private void addDateToUser() {
		BmobRelation dateRecord = new BmobRelation();
		dateRecord.add(App.DateInfo);
		User user = new User();
		user.setObjectId(App.BmobUser.getObjectId());
		user.setDateRecord(dateRecord);
		user.update(this, new UpdateListener() {

			@Override
			public void onSuccess() {
				mProgressDialog.dismiss();
				T.show(AnnounceActivity.this, "发布成功", Toast.LENGTH_SHORT);
				startActivity(new Intent(AnnounceActivity.this,
						MainActivity.class));
				finish();
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				mProgressDialog.dismiss();
				T.show(AnnounceActivity.this, "发布失败" + arg1, Toast.LENGTH_SHORT);
			}
		});
	}

	/**
	 * 
	 * 描述： 返回提示对话框
	 * 
	 * @return void
	 */
	private void showBackDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage("您还没发布,确定返回?");
		builder.setNegativeButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startActivity(new Intent(AnnounceActivity.this,
								MainActivity.class));
						finish();
					}
				});
		builder.setPositiveButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.create().show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showBackDialog();
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			showBackDialog();
			break;
		case R.id.btn_announce_place:
			showPlaceDialog();
			break;
		case R.id.btn_announce_time:
			mTimePickerDialog.show();
			break;
		case R.id.btn_announce_date:
			mDatePickerDialog.show();
			break;
		case R.id.btn_announce_people:
			showPeopleDialog();
			break;
		case R.id.btn_announce_detail:
			showDetailDialog();
			break;
		case R.id.btn_announce:
			announceDate();
			break;
		default:
			break;
		}
	}

}
